# coding : UTF-8
"""
author：BingBO   time：2023.04.14
Theme：
notes：
"""
import cv2 as cv
import numpy as np
import sys

sys.path.append(r"E:\SHU\Research Group\LaserVisionSensor\LaserVisionSensor\Cross_FeaturePointEx\pkgs")
from pkgs import *  # 导入包中 __init__.py指定的模块


def CrossLaser_V(img, laser1_, laser2_, EP1, EP2, CrossPoint):
    P1mid, P1_1, P1_2 = V.LaserExtract(laser1_, 1)
    P2mid, P2_1, P2_2 = V.LaserExtract(laser2_, 2)
    P1_w = [P1_1, P1_2]     #
    P2_w = [P2_1, P2_2]     #
    Com.weldLine(img, P1mid, EP1, P2mid, EP2, CrossPoint, P1_w, P2_w)


def CrossLaser_Square(img, laser1_, laser2_, EP1, EP2, CrossPoint):
    P1mid, P1_1, P1_2 = Square.laser1_Extract(laser1_)  # P1 = [row_gapUp, indexCol1]  # 行，列
    P2mid, P2_1, P2_2 = Square.laser2_Extract(laser2_)
    P1_w = [P1_1, P1_2]
    P2_w = [P2_1, P2_2]
    Com.weldLine(img, P1mid, EP1, P2mid, EP2, CrossPoint, P1_w, P2_w)


def CrossLaser_SingleBevel(img, laser1_, laser2_, EP1, EP2, CrossPoint, sp1, sp2):
    P1, P1_w = SingleBevel.laser1_Extract(laser1_, sp1, EP1)
    P2, P2_w = SingleBevel.laser2_Extract(laser2_, sp2, EP2)
    # P1_w = [fp_y1, fp_x1]  # 行索引，列索引
    Com.weldLine(img, P1, EP1, P2, EP2, CrossPoint, P1_w, P2_w)


def CrossLaser_Lap(img, laser1_, laser2_, EP1, EP2, CrossPoint):
    P1 = Lap.laser1_Extract(laser1_)
    P2 = Lap.laser2_Extract(laser2_)
    Com.weldLine(img, P1, EP1, P2, EP2, CrossPoint)


def gapNum(img, num):
    Red = img[:, :, 2]  # B0 G1 R2
    _, threshold = cv.threshold(Red, 160, 255, cv.THRESH_BINARY)  # 转为二值图
    threshold = cv.medianBlur(threshold, 3)
    cv.imwrite(r"F:\MVS_Data\Roi%d.png" % num, threshold)

    # 求光条的下间断点行坐标
    lightList = np.sum(threshold, axis=0)  # 0 列相加, 变成一行
    ret = np.where(lightList > 0)  # 返回（索引+ 数据类型 ）
    lightIdx = ret[0]
    RightShift = np.roll(lightIdx, 1)  # 向下移动一位
    differList = lightIdx - RightShift
    gap = max(differList) - 1
    print("Roi%d垂直方向的最大gap值 = " % num, gap)
    exist_gap = 0
    if gap >= 2:
        exist_gap = 1
        print("存在间断")
    return exist_gap


def weldTypes(img):
    img = cv.resize(img, None, fx=0.4, fy=0.4, interpolation=cv.INTER_CUBIC)
    # laser1  laser2: 单线全图
    CrossPoint, start_point1, start_point2, laser1, laser2, regionROI = Com.CrossPointlocation_step2(img, 6)

    # 返回工件边缘点坐标
    EP2, EP1 = Com.edgePointlocation(laser2, laser1)
    (realCol_Up, realRow_Up) = EP2
    (realCol_Dn, realRow_Dn) = EP1

    # laser1_  laser2_: 边缘点左边的  仅工件上的光条
    laser1_ = laser1[:, :realCol_Dn + 1]
    laser2_ = laser2[:, :realCol_Up + 1]

    # cv.imshow("laser1_", laser1_)
    cv.imwrite(r"F:\MVS_Data\laser1_.png", laser1_)
    # cv.imshow("laser2_", laser2_)
    cv.imwrite(r"F:\MVS_Data\laser2_.png", laser2_)
    # cv.waitKey(0)
    # cv.destroyAllWindows()

    #
    crossCol, crossRow = CrossPoint
    Roi1, _, _, Roi4 = regionROI  # 4个子区域列表
    Roi2 = laser2_[0:crossRow, crossCol:]  # Roi2
    Roi3 = laser1_[crossRow:, crossCol:]  # Roi3

    type_encode = (gapNum(Roi1, 1), gapNum(Roi2, 2), gapNum(Roi3, 3), gapNum(Roi4, 4))

    #
    if type_encode == (0, 0, 0, 0):
        CrossLaser_V(img, laser1_, laser2_, EP1, EP2, CrossPoint)
        print("Type : V")

    if type_encode == (0, 1, 0, 0) or type_encode == (0, 0, 0, 1):
        CrossLaser_Lap(img, laser1_, laser2_, EP1, EP2, CrossPoint)
        print("Type : Lap")

    if type_encode == (1, 0, 0, 0) or type_encode == (0, 0, 1, 0):
        CrossLaser_SingleBevel(img, laser1_, laser2_, EP1, EP2, CrossPoint, start_point1, start_point2)
        print("Type : SingleBevel")

    if type_encode == (1, 1, 0, 0) or type_encode == (0, 0, 1, 1):
        CrossLaser_Square(img, laser1_, laser2_, EP1, EP2, CrossPoint)
        print("Type : Square")


'''
问题点：
1. 边缘迭代搜索的时候，如果初始窗口就发生间断，会报错："F:\MVS_Data\V\V6_dn_0mm_-15\V6_dn_0mm_-15_4.png"
'''

if __name__ == "__main__":
    # src = cv.imread(r"F:\MVS_Data\V\V6_dn_0mm_-15\V6_dn_0mm_-15_2.png")  # V
    src = cv.imread(r"E:\SHU\Research Group\LaserVisionSensor\MVS_Data\Lap\Lap6_dn_0mm_0\Lap6_dn_0mm_0_16.png")  # Lap
    # src = cv.imread(r"F:\MVS_Data\Square\Square6_dn_2mm_0\Square6_dn_2mm_0_19.png")  # Square
    # src = cv.imread(r"F:\MVS_Data\singleBevel\singleBevel6_up_0mm_-15\singleBevel6_up_0mm_-15_1.png")  # singleBevel

    t1 = cv.getTickCount()
    weldTypes(src)
    t2 = cv.getTickCount()
    print("time: %s ms" % ((t2 - t1) / cv.getTickFrequency() * 1000))

    # cv.waitKey(0)
    cv.destroyAllWindows()
